<?php

namespace app\api\controller;

use app\api\model\Coupons;
use app\api\model\UserCoupons;
use app\common\controller\Api;
use think\Controller;
use think\Request;

class UserCoupon extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 用户优惠券详情
     */
    public function read($user_coupon_id)
    {
        $coupon = UserCoupons::find($user_coupon_id);
        if (!$coupon) {
            $this->error('没有数据', [], 2);
        }
        $coupon['start_time'] = $coupon['start_time'] ? date('Y-m-d', $coupon['start_time']) : '';
        $coupon['end_time'] = $coupon['end_time'] ? date('Y-m-d', $coupon['end_time']) : '';
        $notes = Coupons::where('id', $coupon->coupon_id)->value('notes');
        $coupon['notes'] = $notes ?: '';
        $this->success('请求成功', compact('coupon'));
    }

    /**
     * 用户优惠券详情
     */
    public function readCode()
    {
        $code = $this->request->post('code');
        $coupon = UserCoupons::getByCode($code);
        if (!$coupon) {
            $this->error('没有数据', [], 2);
        }
        $coupon['start_time'] = $coupon['start_time'] ? date('Y-m-d', $coupon['start_time']) : '';
        $coupon['end_time'] = $coupon['end_time'] ? date('Y-m-d', $coupon['end_time']) : '';
        $this->success('请求成功', compact('coupon'));
    }

    /**
     * 核销优惠码
     */
    public function check()
    {
        $code = $this->request->post('code');
        if (empty($code)) {
            $this->error('优惠码不能为空');
        }
        $user_coupon= UserCoupons::getByCode(strtoupper($code));
        if (!$user_coupon) {
            $this->error('用户优惠券不存在');
        }
        if ($user_coupon->status != 1) {
            $this->error('优惠券已过期或已使用');
        }
        $user_coupon->status = 2;
        $result = $user_coupon->save();
        $result ? $this->success('核销成功') : $this->error('核销失败');
    }

}
